package com.wkang.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.wkang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author: wkang
 * @package: com.wkang.controller
 * @date: 2019/11/12
 * @version: ver1.0
 */
@RestController
@RequestMapping("/consumer")
@DefaultProperties(defaultFallback = "failBack")
public class UserController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/{id}")
//    @HystrixCommand(fallbackMethod = "failBack")
    @HystrixCommand
    public User queryById(@PathVariable("id")Integer id){

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
//        List<ServiceInstance> providerList = discoveryClient.getInstances("user_provider");//与serviceId大小写无关
//        ServiceInstance serviceInstance = providerList.get(0);//获取host名称及port
        String url="http://USER-PROVIDER/user/find/"+id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }

    public User failBack(){
        User user=new User();
        user.setUsername("服务降级,默认处理!");
        return  user;

    }
}
